package com.ncucoder.soms.service.impl;

import com.ncucoder.soms.dao.ProductMapper;
import com.ncucoder.soms.dao.ProviderMapper;
import com.ncucoder.soms.dao.UserMapper;
import com.ncucoder.soms.dto.DisplayProductDTO;
import com.ncucoder.soms.dto.DisplayUserDTO;
import com.ncucoder.soms.entity.Product;
import com.ncucoder.soms.entity.User;
import com.ncucoder.soms.service.ProductService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author <a href="https://www.ncucoder.com">hsowan</a>
 * @date 2019-07-15
 **/
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProviderMapper providerMapper;

    @Override
    public int insertProduct(Product product) {

        // 生成唯一的商品编码
        String code = System.currentTimeMillis() + RandomStringUtils.randomAlphanumeric(10);
        product.setCode(code);

        return productMapper.insert(product);
    }

    @Override
    public List<DisplayProductDTO> listProducts(int page, int pageSize) {
        int beginIndex = pageSize * (page - 1);

        List<Product> products = productMapper.selectProducts(beginIndex, pageSize);

        List<DisplayProductDTO> displayProducts = new ArrayList<>();
        for (Product product: products) {
            DisplayProductDTO displayProduct = new DisplayProductDTO();
            displayProduct.setId(product.getId());
            displayProduct.setCode(product.getCode());
            displayProduct.setDesc(product.getDesc());
            displayProduct.setName(product.getName());
            displayProduct.setPrice(product.getPrice());
            displayProduct.setUnit(product.getUnit());
            displayProduct.setProvider(providerMapper.selectProviderById(product.getProviderId()).getName());
            displayProduct.setStock(product.getStock());

            displayProducts.add(displayProduct);
        }
        return displayProducts;
    }

    @Override
    public int countProducts() {
        return productMapper.countProducts();
    }

    @Override
    public int deleteProductById(Long id) {
        return productMapper.deleteProductById(id);
    }
}
